<template>
  <div class="agency-manage">
    <div class="agency-manage-header">
      <span class="agency-manage-header-left">代理商管理</span>
<!--      <span class="agency-manage-header-right">-->
<!--        <el-button type="primary" size="mini" @click="addAgent">添加代理商</el-button>-->
<!--      </span>-->
    </div>
    <div class="agency-manage-search">
      <div class="time">
        创建时间：
        <el-date-picker
          :picker-options="pickerOptions"
          v-model="searchDate"
          type="daterange"
          align="center"
          unlink-panels
          range-separator="|"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleFilter"
        />
        <el-select v-model="indentity" style="width:150px;" @change="handleFilter">
          <el-option
            v-for="item in indentitys"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="status" style="width:150px;" @change="handleFilter">
          <el-option
            v-for="item in statuses"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="keyword">
        关键词:
        <el-select v-model="keyword" clearable style="width:180px;" @change="handleFilter">
          <el-option
            v-for="item in keywords"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input v-model="content" style="width:200px" placeholder="请输入内容" @keyup.enter.native="handleFilter"/>
        <el-button type="primary" style="margin-left:10px;" plain @click="handleFilter">搜索</el-button>
        <el-button size="medium" type="info" @click="clearParams">清空</el-button>
        <el-button :loading="downloadLoading" type="primary" plain @click="handleExport">导出</el-button>
      </div>
    </div>
    <eltable :table-label="tableLabel" :table-data="tableData" style="padding:0 20px; ">
      <el-table-column slot="button" label="操作" min-width="15" align="center">
        <template slot-scope="scope">
          <!--<el-button type="primary" size="small" @click="handleView(scope)">查看</el-button>-->
          <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="primary" size="small" @click="handleStatus(scope)">{{ scope.row.status === '1'? '禁用': '启用' }}</el-button>
        </template>
      </el-table-column>
    </eltable>

    <pagination
      :total="total"
      :current-page="currentpage"
      :page-size="pagesize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />

    <add-dialog v-if="addDialog.dialog" :data="addDialog" @addClosed="addDialog.dialog = false"/>
    <view-dialog v-if="viewDialog.dialog" :data="viewDialog" @viewClosed="viewDialog.dialog = false"/>
    <edit-dialog v-if="editDialog.dialog" :data="editDialog" @editClosed="editDialog.dialog = false" @editSubmit="editSubmit"/>
  </div>
</template>

<script>
import Eltable from '@/components/Eltable'
import Pagination from '@/components/Pagination'
import AddDialog from './components/agency/agencymanage/add'
import ViewDialog from './components/agency/agencymanage/view'
import editDialog from './components/agency/agencymanage/edit'
import { getAgencyManage, getOperateRecord, update } from '@/api/distribution/agencymanage'
import { getTenantId, getUserId } from '@/utils/auth'
import {parseTime} from '@/utils'
export default {
  components: {
    Eltable,
    Pagination,
    AddDialog,
    ViewDialog,
    editDialog
  },
  data() {
    return {
      downloadLoading: false,
      total: 0,
      currentpage: 1,
      pagesize: 10,
      searchDate: [],
      indentity: '',
      status: '',
      keyword: '',
      content: '',
      addDialog: {
        dialog: false,
        linkUrl: ''
      },
      viewDialog: {
        dialog: false,
        tableData: ''
      },
      editDialog: {
        dialog: false,
        tableData: ''
      },
      tableLabel: [
        {
          label: '代理商编号', prop: 'id', width: '10'
        },
        {
          label: '机构/个人名称', prop: 'name', width: '10'
        },
        {
          label: '联系方式', prop: 'phone', width: '10'
        },
        {
          label: '代理商状态', prop: 'statusStr', width: '10'
        },
        {
          label: '代理商身份', prop: 'identityStr', width: '10'
        },
        {
          label: '创建日期', prop: 'createTimeStr', width: '10'
        }
      ],
      tableData: [],
      filterData: [],
      keywords: [
        {
          label: '代理商账号',
          value: 'account'
        },
        {
          label: '机构/个人名称',
          value: 'name'
        },
        {
          label: '联系方式',
          value: 'phone'
        }
      ],
      indentitys: [
        {
          label: '代理商身份',
          value: ''
        },
        {
          label: '个人',
          value: 'personal'
        },
        {
          label: '机构',
          value: 'organization'
        }
      ],
      statuses: [
        {
          label: '代理商状态',
          value: ''
        },
        {
          label: '启用',
          value: '1'
        },
        {
          label: '禁用',
          value: '0'
        }
      ],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    getData() {
      getAgencyManage(getTenantId()).then(res => {
        res.data.items.map(item => {
          if (item.status === '1') item.statusStr = '启用';
          if (item.status === '0') item.statusStr = '禁用';
          if (item.identity === 'org') item.identityStr = '机构';
          if (item.identity === 'person') item.identityStr = '个人'
        });
        this.tableData = res.data.items;
        this.filterData = res.data.items;
        this.total = res.data.items.length
      })
    },
    handleFilter() {
      this.tableData = this.filterData.filter(item => {
        if (this.searchDate && (new Date(item.createTime) < this.searchDate[0] || new Date(item.createTime) > this.searchDate[1])) return false;
        if (this.indentity && item.indentity !== this.indentity) return false;
        if (this.status && item.status !== this.status) return false;
        if (this.keyword === 'account' && item.id.toString().toLocaleLowerCase().indexOf(this.content.toLocaleLowerCase()) < 0) return false;
        if (this.keyword === 'name' && item.name.toLocaleLowerCase().indexOf(this.content.toLocaleLowerCase()) < 0) return false;
        if (this.keyword === 'phone' && item.phone.toLocaleLowerCase().indexOf(this.content.toLocaleLowerCase()) < 0) return false;
        return true
      });
      this.total = this.tableData.length
    },
    clearParams() {
      this.searchDate = [];
      this.indentity = '';
      this.status = '';
      this.keyword = '';
      this.content = '';
      this.getData()
    },
    handleView(scope) {
      this.viewDialog.dialog = true;
      getOperateRecord(getUserId()).then(res => {
        this.viewDialog.tableData = res.data.items
      })
    },
    handleEdit(scope) {
      this.editDialog.tableData = Object.assign({}, scope.row);
      this.editDialog.dialog = true
    },
    editSubmit(form) {
      update(form).then(res => {
        this.editDialog.dialog = false;
        this.getData();
        this.$notify({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    addAgent() {
      this.addDialog.linkUrl = 'https://www.baidu.com';
      this.addDialog.dialog = true
    },
    handleStatus(scope) {
      let content = '';
      const form = Object.assign({}, scope.row);
      if (scope.row.status === '0') {
        form.status = '1';
        content = '此操作将会启用代理商的分销功能，所有的分销活动状态会变成关闭，代理商将不能参加网校的所有分销活动。请确认操作。'
      } else {
        form.status = '0';
        content = '此操作将会禁用代理商的分销功能，所有的分销活动状态会变成开启，若需要关闭代理商其中一个分销活动，请前往该活动设置中的代理商设置模块操作关闭。请确认操作。'
      }
      this.$confirm(content, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.editSubmit(form)
      })
    },
    // 导出按钮
    handleExport() {
      this.downloadLoading = true;
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['代理商编号', '机构/个人名称', '联系方式', '代理商状态', '代理商身份', '创建日期'];
        const filterVal = ['id', 'name', 'phone', 'statusStr', 'identityStr', 'createTime'];
        const list = this.tableData;
        const data = this.formatJson(filterVal, list);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'agencyManageList',
          autoWidth: true,
          bookType: 'xlsx'
        });
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'createTime') {
          return v[j] ? parseTime(v[j]) : v[j]
        } else {
          return v[j]
        }
      }))
    },
    handleSizeChange(val) {
      this.currentpage = 1;
      this.pagesize = val.value;
      if (this.pagesize >= 20) {
        scrollTo(50, 800)
      }
    },
    handleCurrentChange(val) {
      this.currentpage = val.value;
      if (this.pagesize >= 20) {
        scrollTo(50, 800)
      }
    }
  }
}
</script>

<style lang="scss">
.agency-manage {
  &-header {
    color: rgb(52, 172, 228);
    padding: 10px 30px;
    background: #ebf4ff;
    margin-top: 20px;
    overflow: hidden;
    &-right {
      float: right;
      margin-top: 2px;
    }
    &-left {
      font-size: 18px;
      line-height: 1.8;
    }
  }
  .time,
  .keyword {
    width: 100%;
    padding: 15px 20px;
    color: #606266;
    font-size: 14px;
  }
}
</style>
